package com.zeker.spring_ai_zeker.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.zeker.spring_ai_zeker.service.ITalkOfQwenService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;


@Service
@AllArgsConstructor
public class TalkOfQwenServiceImpl implements ITalkOfQwenService {

    @Value("${api.key}")//不能用lombok的@value依赖去读取配置，因为他没有这个作用
    private String apiKey;

    private final String linkMsg = "请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code";

    @Override
    public String getCallMsg(String msg) {
        try {
            return callWithMessage(msg,apiKey);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // 明确处理API Key缺失的情况
            throw new RuntimeException("错误信息：" + e.getMessage() + linkMsg);
        }
    }


    public static String callWithMessage(String msg,String apiKey) throws ApiException, NoApiKeyException, InputRequiredException {
        //装载消息体
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(msg)
                .build();
        //配置秘钥、模型类型、发送消息
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用阿里云百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                // 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models，去这个网站找一个模型model
                .model("qwen-turbo")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        //获取回复消息
        GenerationResult genrationResult = gen.call(param);
        String callMsg = genrationResult.getOutput().getChoices().get(0).getMessage().getContent();

        return callMsg;
    }
}
